# -*-coding:Utf-8 -* 
""" UI Font class
"""
from bge import logic
import bgl, blf

class Font(object):
	_declared_Font = {}
	dpi = 72
		
	def __init__(self, name):
		name = str(name)
		if name not in Font._declared_Font:
			Font._declared_Font[name] = blf.load(logic.expandPath("//resources/fonts/"+name))
		self.name = name
		self._id = Font._declared_Font[name]
		self.loaded = True
		if self._id == -1:
			self.loaded = False
	
	@classmethod			
	def freeAllFonts(cls):
		for aFont in cls._declared_Font.keys():
			if cls._declared_Font[aFont] >= 0:
				blf.unload(logic.expandPath("//resources/fonts/"+aFont))
		cls._declared_Font = {}
				
	def cutByWorld(self, text, width):
		result = ""
		bfr1 = text.splitlines()
		spdim = int(blf.dimensions(self.Id, " ")[0])
		for aLine in bfr1:
			bfr2 = text.split(' ')
			x= int(blf.dimensions(self.Id, bfr2[0])[0])
			result += bfr2[0]
			bfr2.pop(0)
			for aWord in bfr2:
				dim = int(blf.dimensions(self.Id, aWord)[0])
				if dim > (width-x):
					result += '\n'+aWord
					x = dim
				else:
					result += " "+aWord
					x += spdim+dim
			result += '\n'
		return result
	
	@property
	def Id(self):
		return self._id
		
				
		
			
